<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="单位">
              <j-dict-select-tag v-model="queryParam.unit" placeholder="请选择单位" dictCode="unit" />
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <a-form-item label="年度">
              <j-dict-select-tag v-model="queryParam.year" placeholder="请选择年度" dictCode="year" />
            </a-form-item>
          </a-col>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
              <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'" />
              </a>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <!--      <a-button @click="handleAdd" type="primary" icon="plus">新增</a-button>-->
      <!--      <a-button type="primary" icon="download" @click="handleExportXls('收支总表')">导出</a-button>-->
      <!--      <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl" @change="handleImportExcel">-->
      <!--        <a-button type="primary" icon="import">导入</a-button>-->
      <!--      </a-upload>-->
      <!--      &lt;!&ndash; 高级查询区域 &ndash;&gt;-->
      <!--      <j-super-query :fieldList="superFieldList" ref="superQueryModal" @handleSuperQuery="handleSuperQuery"></j-super-query>-->
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel"><a-icon type="delete" />删除</a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px"> 批量操作 <a-icon type="down" /></a-button>
      </a-dropdown>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{
          selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table ref="table" size="middle" :scroll="{ x: true }" bordered rowKey="id" :columns="columns"
        :dataSource="dataSource" :pagination="ipagination" :loading="loading"
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }" class="j-table-force-nowrap"
        @change="handleTableChange">

        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="imgSlot" slot-scope="text,record">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
          <img v-else :src="getImgView(text)" :preview="record.id" height="25px" alt=""
            style="max-width:80px;font-size: 12px;font-style: italic;" />
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
          <a-button v-else :ghost="true" type="primary" icon="download" size="small" @click="downloadFile(text)">
            下载
          </a-button>
        </template>
        <!-- 操作列：待审批状态仅显示审批详情，无任何分界线 -->
        <template slot="action" slot-scope="text, record">
          <!-- 只有当状态为"待审批"时才显示审批按钮 -->
          <a v-if="record.state === '待审批'||record.state === '第一人审批同意'" @click="openApprovalModal(record)">审批</a>
          <!-- 如果显示了审批按钮，才显示分隔线 -->
          <a-divider v-if="record.state === '待审批'||record.state === '第一人审批同意'" type="vertical" />
          <a @click="openApprovalMessageDrawer(record.id)">审批详情</a>
        </template>

      </a-table>
    </div>
    <!-- table区域 end -->

    <!-- 审批弹框（包含状态下拉和留言输入） -->
    <a-modal title="审批处理" v-model="approvalModalVisible" ok-text="确认审批" cancel-text="取消" @ok="handleApprovalConfirm"
      @cancel="approvalModalVisible = false">
      <!-- 修复label-col属性类型错误，使用对象形式配置栅格 -->
      <a-form :model="approvalForm" layout="vertical" :label-col="{ span: 6 }" :wrapper-col="{ span: 16 }">
        <!-- 审批状态下拉框 -->
        <a-form-item label="审批结果">
          <a-select v-model="approvalForm.approvalResult" placeholder="请选择审批结果" style="width: 100%" required>
            <a-select-option value="通过">通过</a-select-option>
            <a-select-option value="驳回">驳回</a-select-option>
          </a-select>
        </a-form-item>
        <!-- 审批留言输入框 -->
        <a-form-item label="审批留言">
          <a-textarea v-model="approvalForm.approvalRemark" placeholder="请输入审批意见（可选）" rows="4"
            style="width: 100%"></a-textarea>
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 审批详情抽屉（展示CwApprovalMessageList） -->
    <cw-approval-message-drawer ref="approvalMessageDrawer" @ok="handleApprovalMessageOk"></cw-approval-message-drawer>
    <cw-szzb-modal ref="modalForm" @ok="modalFormOk"></cw-szzb-modal>
  </a-card>
</template>

<script>

import '@/assets/less/TableExpand.less'
import { mixinDevice } from '@/utils/mixin'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import CwSzzbModal from './modules/CwSzzbModal'
import { filterMultiDictText } from '@/components/dict/JDictSelectUtil'
import CwApprovalMessageDrawer from './modules/CwApprovalMessageModal.Style#Drawer.vue'

export default {
  name: 'CwSzzbList',
  mixins: [JeecgListMixin, mixinDevice],
  components: {
    CwApprovalMessageDrawer,
    CwSzzbModal
  },
  data() {
    return {
      description: '收支总表管理页面',
      // 表头
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: "center",
          customRender: function (t, r, index) {
            return parseInt(index) + 1;
          }
        },
        {
          title: '单位',
          align: "center",
          dataIndex: 'unit'
        },
        {
          title: '年度',
          align: "center",
          dataIndex: 'year'
        },
        {
          title: '一般公共预算拨款收入',
          align: "center",
          dataIndex: 'ybgg'
        },
        {
          title: '国有资本经营预算拨款收入',
          align: "center",
          dataIndex: 'gyzb'
        },
        {
          title: '事业收入',
          align: "center",
          dataIndex: 'sysr'
        },
        {
          title: '其他收入',
          align: "center",
          dataIndex: 'qtsr'
        },
        {
          title: '使用非财政拨款结余',
          align: "center",
          dataIndex: 'fc'
        },
        {
          title: '一般公共预算结转资金',
          align: "center",
          dataIndex: 'ybggys'
        },
        {
          title: '国有资本经营预算结转资金',
          align: "center",
          dataIndex: 'gyzbjy'
        },
        {
          title: '其他资金',
          align: "center",
          dataIndex: 'qtzj'
        },
        {
          title: '社会保障和就业支出（离退休经费）',
          align: "center",
          dataIndex: 'shbz'
        },
        {
          title: '农业产业发展资金',
          align: "center",
          dataIndex: 'nycy'
        },
        {
          title: '农业经营主体能力提升资金',
          align: "center",
          dataIndex: 'nyjy'
        },
        {
          title: '非财项目',
          align: "center",
          dataIndex: 'fcxm'
        },
        {
          title: '农村社会事业（中央基建投资）',
          align: "center",
          dataIndex: 'ncshsy'
        },
        {
          title: '其他农业农村支出（中央基建投资）',
          align: "center",
          dataIndex: 'qtnynczc'
        },
        {
          title: '住房保障支出',
          align: "center",
          dataIndex: 'zfbzzc'
        },
        {
          title: '北大荒农垦改革发展过渡期补助',
          align: "center",
          dataIndex: 'nkgg'
        },
        {
          title: '黑龙江垦区社会公益性事务专项经费',
          align: "center",
          dataIndex: 'hlj'
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: "center",
          fixed: "right",
          width: 147,
          scopedSlots: { customRender: 'action' }
        }
      ],
      url: {
        list: "/cw/cwSzzb/list",
        delete: "/cw/cwSzzb/delete",
        deleteBatch: "/cw/cwSzzb/deleteBatch",
        exportXlsUrl: "/cw/cwSzzb/exportXls",
        importExcelUrl: "cw/cwSzzb/importExcel",
        approval: '/cw/cwSzzb/approval' // 审批接口
      },
      superFieldList: [],
      approvalModalVisible: false, // 审批弹框显示状态
      currentApprovalRecord: null, // 当前待审批的记录
      approvalForm: {
        approvalResult: '', // 审批结果：通过/驳回
        approvalRemark: '' // 审批留言
      }
    }
  },
  created() {
    this.getSuperFieldList();
  },
  computed: {
    importExcelUrl: function () {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
    },
    // 审批接口完整地址
    approvalUrl() {
      return window._CONFIG['domianURL'] + this.url.approval
    }
  },
  methods: {
    initDictConfig() {
    },
    getSuperFieldList() {
      let fieldList = [];
      fieldList.push({ type: 'string', value: 'unit', text: '单位', dictCode: 'unit' })
      fieldList.push({ type: 'string', value: 'year', text: '年度', dictCode: 'year' })
      fieldList.push({ type: 'double', value: 'ybgg', text: '一般公共预算拨款收入', dictCode: '' })
      fieldList.push({ type: 'double', value: 'gyzb', text: '国有资本经营预算拨款收入', dictCode: '' })
      fieldList.push({ type: 'double', value: 'sysr', text: '事业收入', dictCode: '' })
      fieldList.push({ type: 'double', value: 'qtsr', text: '其他收入', dictCode: '' })
      fieldList.push({ type: 'double', value: 'fc', text: '使用非财政拨款结余', dictCode: '' })
      fieldList.push({ type: 'double', value: 'ybggys', text: '一般公共预算结转资金', dictCode: '' })
      fieldList.push({ type: 'double', value: 'gyzbjy', text: '国有资本经营预算结转资金', dictCode: '' })
      fieldList.push({ type: 'double', value: 'qtzj', text: '其他资金', dictCode: '' })
      fieldList.push({ type: 'double', value: 'shbz', text: '社会保障和就业支出（离退休经费）', dictCode: '' })
      fieldList.push({ type: 'double', value: 'nycy', text: '农业产业发展资金', dictCode: '' })
      fieldList.push({ type: 'double', value: 'nyjy', text: '农业经营主体能力提升资金', dictCode: '' })
      fieldList.push({ type: 'double', value: 'fcxm', text: '非财项目', dictCode: '' })
      fieldList.push({ type: 'double', value: 'ncshsy', text: '农村社会事业（中央基建投资）', dictCode: '' })
      fieldList.push({ type: 'double', value: 'qtnynczc', text: '其他农业农村支出（中央基建投资）', dictCode: '' })
      fieldList.push({ type: 'double', value: 'zfbzzc', text: '住房保障支出', dictCode: '' })
      fieldList.push({ type: 'double', value: 'nkgg', text: '北大荒农垦改革发展过渡期补助', dictCode: '' })
      fieldList.push({ type: 'double', value: 'hlj', text: '黑龙江垦区社会公益性事务专项经费', dictCode: '' })
      this.superFieldList = fieldList
    },
    // 打开审批弹框
    openApprovalModal(record) {
      this.currentApprovalRecord = record
      // 重置审批表单
      this.approvalForm = {
        approvalResult: '',
        approvalRemark: ''
      }
      this.approvalModalVisible = true
    },

    // 确认审批
    handleApprovalConfirm() {
      // 校验审批结果
      if (!this.approvalForm.approvalResult) {
        this.$message.warning('请选择审批结果（通过/驳回）')
        return
      }

      // 校验记录ID
      if (!this.currentApprovalRecord || !this.currentApprovalRecord.id) {
        this.$message.error('缺少待审批记录信息')
        this.approvalModalVisible = false
        return
      }

      // 发起审批请求
      this.loading = true
      this.$http({
        url: this.approvalUrl,
        method: 'post',
        headers: this.tokenHeader,
        params: {
          id: this.currentApprovalRecord.id,
          approvalResult: this.approvalForm.approvalResult,
          approvalRemark: this.approvalForm.approvalRemark
        }
      }).then(res => {
        if (res.success) {
          this.$message.success('审批操作成功！')
          this.loadData() // 刷新列表
        } else {
          this.$message.error(res.message || '审批操作失败')
        }
      }).catch(err => {
        this.$message.error('审批出错：' + (err.message || err.toString()))
      }).finally(() => {
        this.loading = false
        this.approvalModalVisible = false
      })
    },
    // 打开审批详情抽屉
    openApprovalMessageDrawer(recordId) {
      this.$refs.approvalMessageDrawer.open(recordId)
    },

    // 审批详情抽屉确认回调
    handleApprovalMessageOk() {
      // 可在此处处理刷新逻辑（如刷新当前列表）
    },
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>